#include <iostream>
#include <fstream>

#include "../t509/crypto.h"
#include "../md5/md5.h"
#include "lzma-helper.h"
using namespace std;

#define SODA "dxyl.bin"
#define SLCLIENT "slonline.exe"

int main()
{
    int hr = 0;

    // compress SODA
    {
        cout << "Ready to compress SODA" << endl;
        bool success = LzmaHelper::CompressFile("dxyl.bin", "soda_encrypted.dat");
        if(success)
        {
            cout << "SODA compressed" << endl;
        }
        else
        {
            cout << "SODA is NOT compressed" << endl;
            hr = -1;
            goto end;
        }
    }

    // compute SLCLIENT MD5 hash and encrypt it
    {
        ifstream is;

        is.open(SLCLIENT, ios::binary);
        if(is.bad())
        {
            //LOG_ERROR(L"Failure opening file, s=%s", path);
            cout << "error, cannot open file: " << SLCLIENT << endl;
            hr = -1;
            goto end;
        }

        // get length of the input file:
        is.seekg (0, ios::end);
        auto ilen = is.tellg();
        is.seekg (0, ios::beg);

        unsigned char* ibuff = new unsigned char[ilen];
        is.read((char*)ibuff, ilen);

        unsigned char md5[16];
        MD5CryptoServiceProvider(md5, ibuff, ilen);
        delete[] ibuff;
        is.close();

        cout << "original md5 = {" << hex;
        for(int i=0; i<16; i++)
		    cout << (int)md5[i];
        cout << dec << "};" << endl;

        unsigned char sealed_md5[16] = {0};
		ShiningloreCryptoCache::getRijndaelEncrypter()->encrypt(md5, 16, sealed_md5);

        cout << "sealed_md5 = {" << hex;
        for(int i=0; i<16; i++)
		    cout << (int)sealed_md5[i];
        cout << dec << "};" << endl;

        // output
        ofstream of("hash.inc");

        of << "//" << __TIMESTAMP__ << endl;

        of << "#define ORIGINAL_HASH {" << hex;
        for(int i=0; i<16; i++)
		    of << "0x" << (int)md5[i] << ",";
        long pos = of.tellp();
        of.seekp( pos - 1 ); // go back 1 byte to remove the last ','
        of << dec << "}" << endl;

        of << "#define SEALED_HASH {" << hex;
        for(int i=0; i<16; i++)
		    of << "0x" << (int)sealed_md5[i] << ",";
        pos = of.tellp();
        of.seekp( pos - 1 ); // go back 1 byte to remove the last ','
        of << dec << "}" << endl;
        
        of.close();
    }

    end:
    return hr;
}